import {Button, Layout, Statistic} from "antd";
import {Checkbox, Toast} from 'antd-mobile';
import ShoppingCarCard from "./ShoppingCarCard";
import React, {useContext, useEffect, useState} from "react";
import {useNavigate, useParams} from "react-router-dom";
import TabBar from "../../components/TabBar/TabBar";
import "./shoppingCar.css";
import Search from "antd/es/input/Search";
import {GlobalContext} from "../../contexts/GlobalContext";
const { Header, Footer,Content } = Layout;

const ShoppingCar = () => {
    //权限校验：登录后才能看到购物车，否则提示登录
    const { user } = useContext(GlobalContext);
    const globalContext = useContext(GlobalContext);

    useEffect(() => {
        console.log(123)
        testLogin();
    }, );

    const testLogin = () =>{
        //console.log(localStorage.getItem("username"))
        if(localStorage.getItem("username")!=='user'){
            console.log(user.username)
            navigate('/login')
        }
    }

    const initialTabIndex=2

    const navigate=useNavigate();
    const [cart,setCart] = useState(() => {
        // 从 localStorage 中读取 cart 的初始值，如果不存在则默认为空
        return JSON.parse(localStorage.getItem("cart")) || [];
    });
    //是否全选
    const [allChecked,setAllChecked] = useState(false);
    //购物车商品总数
    const [totalLength,setTotalLength] = useState(cart.length);
    //购物车商品总价
    const [totalPrice,setTotalPrice] = useState(0);
    //是否显示删除按钮
    const [showDelete,setShowDelete] = useState(false);



    //点击“管理”切换是否显示删除按钮
    const isDelete=()=>{
        setShowDelete(prevState => !prevState);
    };
    //勾选/取消全选：更新购物车中所有商品为当前勾选状态
    const chooseAllCheck=(e)=>{
        if(e){
            setAllChecked(true);
        }else{
            setAllChecked(false);
        }
        const updatedCart = cart.map((item) => {
            return {
                ...item,
                isChecked: e
            };
        });
        updateCart(updatedCart);
        localStorage.setItem('cart',JSON.stringify(updatedCart));
    };
    //监听cart的变化，对cart内每个商品，根据是否选中更新总价，根据数量变化修改总数
    useEffect(() => {
        setTotalLength(cart.reduce((total, item) => total + item.count, 0));
        setTotalPrice(cart.reduce((total, item) => {
            if (item.isChecked) {
                return total + item.count * item.price;
            }
            return total;
        }, 0));
    }, [cart]);
    //更新购物车
    const updateCart=(updatedCart)=>{
        setCart(updatedCart);
    };
    //将当前购物车构造为一个订单，跳转到订单页面
    const gotoOrder=()=>{
        const orderList =JSON.parse(localStorage.getItem("orderList"))||[];
        const orderProduct = cart.filter((item)=>
            item.isChecked === true
        );
        if(orderProduct && orderProduct.length !== 0){
            let order = {
                orderId: orderList.length+1,
                productList: orderProduct,
                cost: totalPrice,
                userId: 'user_001',
                address: '某某省,某某市,某某街道',
                discount: 0,
                shipping: 10,
                note: '请尽快发货',
                paymentMethod: '在线支付',
                submitTime: new Date(),
                status: '待付款'
            };
            orderList.push(order);
            localStorage.setItem("orderList",JSON.stringify(orderList));
            navigate(`/order/${order.orderId}`);
        }else if(orderProduct.length === 0){
            Toast.show({
                content: '请选择商品下单',
                position:'bottom',
            });
        }
    };
    //搜索当前购物车内商品，按照商品名称是否包含输入进行过滤，不符合条件的通过isShow隐藏。如果不输入，显示所有商品。
    const searchProduct=(value)=> {
        if(value.trim()!==''){
            const filteredProducts = cart.filter(product =>
                !product.productName.includes(value));
            filteredProducts.forEach((item) => {
                const index = cart.findIndex((p) => p.id === item.id);
                if (index !== -1) {
                    cart[index].isShow = false;
                }
            });
        }else{
            cart.forEach((item) => {
                item.isShow = true;
            });
        }
        setCart(cart);
        localStorage.setItem("cart", JSON.stringify(cart));
        setTimeout(function(){
            window.location.reload();
        },200);
    }
    return(
       <Layout style={{ margin: 'auto', backgroundColor: '#fff' }}>
           <Header style={{
               backgroundColor:'#fff',
               height: '60px',
               fontSize: '20px',
               color: '#FB5B40',
               position:'relative'
                }}>
               <span style={{position:'absolute',left:'15px',textAlign:'center',lineHeight:'60px',fontSize:'24px'}}>购物车</span>
               <span style={{position:'absolute',left:'90px',textAlign:'center',lineHeight:'60px',marginTop:"5px",fontSize:'15px'}}>
                    ({totalLength})
               </span>
               <Search placeholder="请输入商品名称关键字" onSearch={searchProduct} enterButton
                       style={{
                           width: "50%",
                           position:'absolute',
                           left:"50%",
                           transform:"translateX(-45%)",
                           top:"calc(50% - 20px)"
                       }}
               />
               <span style={{position:'absolute',right:'15px',textAlign:'center',lineHeight:'60px'}} onClick={isDelete}>{showDelete?"取消":"管理"}</span>
           </Header>

           <Content style={{backgroundColor:"#efefef",padding:'5px'}}>
               {/*    子组件，购物车商品列表*/}
               <ShoppingCarCard updateCart={updateCart} showDelete={showDelete}></ShoppingCarCard>
           </Content>

           <Footer style={{
               bottom:"60px",
               backgroundColor:"grey",
               position:'fixed',
               width:"100%",
               height:"60px",
           }}>
               <Checkbox style={{
                   position:'absolute',
                   left:'10px',
                   width:"100px",
                   top:"calc(50% - 15px)",
               }}
               checked={allChecked}
               onChange={(e)=>{chooseAllCheck(e)}}
               >全选</Checkbox>
               <span style={{fontSize:"15px",position:"absolute",top:"calc(50%-5px)",right:"190px"}}>合计:</span>
               <Statistic value={'￥'+totalPrice} style={{
                   position:'absolute',
                   right:'100px',
                   height:"20px",
                   top:"calc(50% - 22px)",
                   textAlign:"center"}}
                    />
               <button className="gradient-button"  onClick={gotoOrder}>结算</button>
           </Footer>
           <TabBar initialTabIndex={initialTabIndex}/>
       </Layout>

    );
};
export default ShoppingCar;